import React, { ChangeEvent, useState } from 'react';
import { Box, MainButton, Text, TextArea } from '@nova-hf/ui';
import { MainColorType } from '@nova-hf/ui/umd/ts/src/styles/vars.css';
import Steps from 'beta/store/steps';
import { formatDate } from 'beta/utils/helpers';
import { useTranslation } from 'beta/utils/i18n';
import { inject } from 'mobx-react';
import Link from 'next/link';
import {
  AppointmentInfoInput,
  ConnectionOptions,
  Contract,
  ContractItemType,
  ContractRequestType,
  FiberProvider,
  FiberService,
  ProviderAddress,
  ProviderApartment,
  ServiceRequestType,
  useAddItemsToCartMutation,
  useCreateOrderMutation,
  useFiberOrderQuery,
} from 'typings/graphql';

import AccordionWrapper from '../components/AccordionWrapper';

import { ActivateFiber } from './ActivateFiberStep';
import Address from './Address';
import { FiberInstallation } from './FiberInstallationStep';
import { FiberTerminationStep } from './FiberTerminationStep';

interface CompleteFlutningurProps {
  color: MainColorType;
  steps?: Steps;
  service: FiberService;
  contract: Contract;
}

interface FiberLocationSelection {
  address: ProviderAddress;
  property: ProviderApartment;
  option: ConnectionOptions;
}

const CompleteFlutningur = inject('steps')(({
  color,
  steps,
  service,
  contract,
}: CompleteFlutningurProps) => {
  const { t } = useTranslation('flutningur');

  const [selection, setSelection] = useState<FiberLocationSelection>();
  const [activationDate, setActivationDate] = useState<Date>();
  const [terminationDate, setTerminationDate] = useState<Date>();
  const [selectedSlot, setSelectedSlot] = useState<AppointmentInfoInput | undefined>();
  const [isSubmitted, setIsSubmitted] = useState(false);
  const [optionalDescription, setOptionalDescription] = useState('');

  const [addToCart, { loading: cartLoading, error: cartError }] = useAddItemsToCartMutation();
  const [createOrder, { loading: orderLoading, error: orderError }] = useCreateOrderMutation();

  const serviceContractItem = contract.contractItems.find(
    (c) =>
      c.type == ContractItemType.Service &&
      c.status == 'Active' &&
      !['nova-ljosleidaratenging', 'linubirgi-ljosleidaratenging'].includes(c.variantId!),
  );

  const { data: fiberOrderData } = useFiberOrderQuery({
    variables: {
      input: {
        fiberOrderId: service.fiberOrderId,
      },
    },
  });

  const onConfirm = async () => {
    if (selection?.address && selection.property && selection.option) {
      const addToCartInput = {
        variables: {
          input: {
            customer: {
              ssn: service.user?.nationalId,
            },
            items: [
              {
                variantId: serviceContractItem?.variantId,
                quantity: 1,
                purchaseInfo: {
                  contract: {
                    type: ContractRequestType.Existing,
                    id: contract.id,
                  },
                  service: {
                    type: fiberOrderData?.fiberOrder?.isCompanyOrder
                      ? ServiceRequestType.CompanyFiber
                      : ServiceRequestType.IndividualFiber,
                    user: {
                      name: service.user?.name,
                      customerId: service.userId,
                      nationalId: service.user?.nationalId,
                      email: service.user?.email,
                      phoneNumber: service.user?.primaryPhoneNumber,
                    },
                    provider: selection.option.provider
                      ? selection.option.provider
                      : FiberProvider.Unknown,
                    propertyId: selection.property.propertyId!,
                    propertyIdOrigin: selection.property.propertyIdOrigin!,
                    address: selection.address.line,
                    apartment: selection.property.apartmentNumber,
                    postalCode: selection.address.postCode,
                    municipality: selection.address.city,
                    needsVisit: selection.option.needsVisit,
                    optionalDescription: optionalDescription,
                    moveOrderDetails: {
                      currentServiceId: service.id,
                      currentAddress: service.name,
                      currentServiceTerminationDate: terminationDate!,
                    },
                    ...(activationDate && { activationDate: activationDate }),
                    ...(selectedSlot && {
                      appointment: selectedSlot,
                    }),
                  },
                },
              },
            ],
          },
        },
      };

      const { data } = await addToCart(addToCartInput);

      if (data?.addItemsToCart.cart?.id) {
        const res = await createOrder({
          variables: {
            input: {
              cartId: data.addItemsToCart.cart.id,
            },
          },
        });

        if (res.data?.createOrder.order?.id) {
          setIsSubmitted(true);
        }
      }
    }
  };

  return (
    <Box paddingY={0} paddingRight={{ sm: 1, xl: 9 }} marginBottom={30} width="100%">
      <AccordionWrapper
        title={t('accordion.address.title')}
        subtitle={selection?.address.line ?? ''}
        icon="home"
        color={color}
        stepNumber={1}
      >
        <Address
          color={color}
          onComplete={(a, p, o) => {
            steps?.setAccordionStep(2);
            steps?.setCompletedStep(1);
            setSelection({
              address: a,
              property: p,
              option: o,
            });
          }}
        />
      </AccordionWrapper>
      <AccordionWrapper
        title={
          selection?.option.needsVisit
            ? 'Bóka heimsókn'
            : `Hvenær flyturðu inn${
                selection?.address.street ? ` á ${selection.address.street}` : ''
              }?`
        }
        subtitle=""
        icon="calendar"
        color={color}
        stepNumber={2}
      >
        <>
          {selection && selection.property && selection.option && selection?.option.needsVisit ? (
            <FiberInstallation
              color={color}
              propertyId={selection.property.propertyId!}
              provider={selection.option.provider!}
              userNationalId={service?.user?.nationalId ?? ''}
              onComplete={(slot) => {
                steps?.setAccordionStep(3);
                steps?.setCompletedStep(2);
                setSelectedSlot(slot);
              }}
            />
          ) : (
            <ActivateFiber
              onComplete={(date) => {
                steps?.setAccordionStep(3);
                steps?.setCompletedStep(2);
                setActivationDate(date);
              }}
              provider={selection?.option.provider as FiberProvider}
              color={color}
            />
          )}
          <Box marginX={{ xl: 2 }} marginBottom={{ md: 2 }} marginTop={{ md: 5 }}>
            <TextArea
              id={'optionalDescription'}
              label="Skilaboð til þjónustuaðila"
              name="optionalDescription"
              type="text"
              value={optionalDescription}
              onChange={(e: ChangeEvent<HTMLTextAreaElement>) =>
                setOptionalDescription(e.target.value)
              }
            />
          </Box>
        </>
      </AccordionWrapper>
      <AccordionWrapper
        title="Hvenær flyturðu út?"
        subtitle={''}
        icon="calendar"
        color={color}
        stepNumber={3}
      >
        <FiberTerminationStep
          installationDate={
            activationDate
              ? new Date(activationDate)
              : selectedSlot
              ? new Date(selectedSlot.startTime!)
              : new Date()
          }
          color={color}
          onComplete={(date) => {
            steps?.setAccordionStep(4);
            steps?.setCompletedStep(3);
            setTerminationDate(date);
          }}
        />
      </AccordionWrapper>
      <AccordionWrapper
        title="Staðfesta"
        subtitle={''}
        icon="calendar"
        color={color}
        stepNumber={4}
      >
        <Box>
          <Text>
            {t('flutningur.new.confirm.address')} {selection?.address.line}
          </Text>
          <Text>
            {t('flutningur.new.confirm.apartment')} {selection?.property.apartmentNumber} (
            {selection?.property.propertyId})
          </Text>
          <Text>
            {t('flutningur.new.confirm.vendor')} {selection?.option.provider}
          </Text>
          {selectedSlot?.startTime && (
            <Text>
              {t('flutningur.new.confirm.setupTime')}{' '}
              {formatDate(selectedSlot.startTime, 'dd.MM.yyyy - HH:mm')}
            </Text>
          )}
          {selection?.option.needsVisit && !selectedSlot && (
            <Text>{t('flutningur.new.confirm.setupCall')}</Text>
          )}

          {activationDate ? (
            <Text>
              {t('flutningur.new.confirm.activation')}{' '}
              {formatDate(activationDate, 'dd.MM.yyyy - HH:mm')}
            </Text>
          ) : selection?.option?.provider === FiberProvider.Tengir ? (
            <Text>{t('flutningur.new.confirm.tengir')} </Text>
          ) : null}

          {terminationDate && (
            <Text>
              {t('flutningur.new.confirm.termination')}{' '}
              {formatDate(terminationDate, 'dd.MM.yyyy - HH:mm')}
            </Text>
          )}
          {cartError && (
            <Text>
              {t('flutningur.new.confirm.error')} {cartError.message}
            </Text>
          )}
          {orderError && (
            <Text>
              {t('flutningur.new.confirm.error')} {orderError.message}
            </Text>
          )}
          {isSubmitted ? (
            <>
              <Text>{t('flutningur.new.confirm.confirmed')}</Text>
              <MainButton
                text={t('flutningur.new.confirm.doneButton')}
                wrapper={(link) => (
                  <Link
                    href={`/beta/${service.userId}/thjonustur/${service.id}`}
                    passHref
                    legacyBehavior
                  >
                    {link}
                  </Link>
                )}
              />
            </>
          ) : (
            <MainButton
              onClick={onConfirm}
              text="Staðfesta"
              isLoading={cartLoading || orderLoading}
            />
          )}
        </Box>
      </AccordionWrapper>
    </Box>
  );
});

export default CompleteFlutningur;
